package com.audio;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class AudioPlayer implements Runnable {
    private final BlockingQueue<String> playQueue = new LinkedBlockingQueue<>();
    private volatile boolean isRunning = true;
    private volatile boolean stopCurrent = false; // 新增标志位控制当前播放

    public BlockingQueue<String> getPlayQueue() {
        return playQueue;
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

    // 添加音频到队列
    public void addToQueue(String audioPath) {
        playQueue.offer(audioPath);
    }

    // 清空队列并停止当前播放
    public void stopAndClear() {
        playQueue.clear();
        stopCurrent = true; // 触发停止当前播放
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                String audioPath = playQueue.take();
                playAudio(audioPath);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }

    // 核心播放方法（使用SourceDataLine）
    private void playAudio(String audioPath) {
        AudioInputStream audioStream = null;
        SourceDataLine line = null;

        try {
            // 1. 加载音频流
            audioStream = AudioSystem.getAudioInputStream(new File(audioPath));
            AudioFormat format = audioStream.getFormat();

            // 2. 检查格式兼容性
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            if (!AudioSystem.isLineSupported(info)) {
                System.err.println("不支持的音频格式: " + format);
                return;
            }

            // 3. 打开音频设备
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(format);
            line.start();

            //System.out.println("▶ 开始播放: " + audioPath);

            // 4. 流式传输音频数据（新增stopCurrent检查）
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = audioStream.read(buffer)) != -1 && isRunning && !stopCurrent) {
                line.write(buffer, 0, bytesRead);
            }

            // 5. 等待播放完成（如果未被中断）
            if (!stopCurrent) {
                Thread.sleep(800);
                line.drain();
                //System.out.println("✓ 播放完成: " + audioPath);
            } else {
                //System.out.println("✗ 播放中止: " + audioPath);
            }

        } catch (UnsupportedAudioFileException e) {
            System.err.println("错误的音频格式: " + e.getMessage());
        } catch (LineUnavailableException e) {
            System.err.println("音频设备被占用: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("文件读取失败: " + e.getMessage());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 6. 释放资源并重置标志
            if (line != null) {
                line.stop();
                line.close();
            }
            if (audioStream != null) {
                try {
                    audioStream.close();
                } catch (IOException e) {
                    System.err.println("流关闭异常: " + e.getMessage());
                }
            }
            stopCurrent = false; // 重置停止标志
        }
    }
}